package com.jinlejia.erp.ui.mine.actual;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListInterface;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.ListMapDropDownAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.FragmentActualSellingBinding;
import com.jinlejia.erp.ui.house.HouseDetailActivity;
import com.jinlejia.erp.ui.mine.adapter.ActualRentAdapter;
import com.jinlejia.erp.ui.mine.adapter.TimeDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;


/**
 * 实勘（出租）
 */

public class ActualRentFragment extends Fragment implements OnDateSetListener, YfLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    private View view;
    private String headers[] = {"房源编号", "审核状态", "小区名称", "提交时间"};
    //    private String state[] = {"不限", "待审核", "通过", "驳回"};
    private String time[] = {"最早日期", "最晚日期"};

    private List<View> popupViews = new ArrayList<>();
    private TextView confirm1;
    private TextView confirm2;
    private EditText causeNumber1;
    private EditText causeNumber2;

    private ListMapDropDownAdapter stateMenuAdapter;
    private TimeDropDownAdapter timeAdapter;
    private ActualRentAdapter adapter;

    private ListView mStateView;
    private ListView mTimeView;

    public String startTime = "";
    public String endTime = "";
    public String house_number = "";
    public String rscode_number = "";
    public String contractCode = "";

    private JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private ArrayList<Map<String, Object>> stateList = new ArrayList<>();
    private InputMethodManager imm;

    private FragmentActualSellingBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_actual_selling, container, false);
        binding = DataBindingUtil.bind(view);

        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        initEvent();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        page = 1;
        getData();
    }

    private void initView() {
        binding.include.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.include.refreshLayout.setOnRefreshListener(this);
        //init houseNumber  menu
        final View houseFooter = getActivity().getLayoutInflater().inflate(R.layout.item_search_footer, null);
        binding.include.dropDownMenu.setTabText(headers[0]);
        //房源编号输入框
        causeNumber1 = houseFooter.findViewById(R.id.search_edit);
        causeNumber1.setHint("请输入房源编号");
        //搜索按钮
        confirm1 = houseFooter.findViewById(R.id.search_text);

        //init state menu
        mStateView = new ListView(getActivity());
        stateMenuAdapter = new ListMapDropDownAdapter(getContext(), stateList);
        mStateView.setAdapter(stateMenuAdapter);

        //init houseNumber  menu
        final View CommunityFooter = getActivity().getLayoutInflater().inflate(R.layout.item_search_footer, null);
        binding.include.dropDownMenu.setTabText(headers[2]);
        //小区名称输入框
        causeNumber2 = CommunityFooter.findViewById(R.id.search_edit);
        causeNumber2.setHint("请输入小区名称");
        //搜索按钮
        confirm2 = CommunityFooter.findViewById(R.id.search_text);

        //init time menu
        final View priceAreaFooter = getActivity().getLayoutInflater().inflate(R.layout.time_menu_footer, null);
        mTimeView = new ListView(getActivity());
        timeAdapter = new TimeDropDownAdapter(getContext(), Arrays.asList(time));
        mTimeView.addFooterView(priceAreaFooter);
        mTimeView.setAdapter(timeAdapter);

        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm = priceAreaFooter.findViewById(R.id.bt_confirm);

        //点击重置
        cancel.setOnClickListener(v -> {
            timeAdapter.startTime = "";
            timeAdapter.endTime = "";
            startTime = "";
            endTime = "";
            binding.include.dropDownMenu.setTabText("提交时间");
            timeAdapter.notifyDataSetChanged();
        });

        //确定按钮
        confirm.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(startTime) || !TextUtils.isEmpty(endTime)) {
                jsonObject.put("dataMin", startTime);
                jsonObject.put("dataMax", endTime);
            } else {
                jsonObject.remove("dataMin");
                jsonObject.remove("dataMax");
            }
            getData();
            binding.include.dropDownMenu.closeMenu();
        });

        popupViews.add(houseFooter);//添加房源编号菜单
        popupViews.add(mStateView);//添加审核状态菜单
        popupViews.add(CommunityFooter);//添加小区名称菜单
        popupViews.add(mTimeView);//添加提交时间


        TextView contentView = new TextView(getActivity());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);

        //init dropdownview
        binding.include.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        binding.include.contractRecyclerView.setHasFixedSize(true);
        binding.include.contractRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.include.contractRecyclerView.enableAutoLoadMore(this);

        adapter = new ActualRentAdapter(dataList);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.include.contractRecyclerView.setAdapter(adapter);

    }

    /**
     * 初始化事件
     */
    private void initEvent() {

        mStateView.setOnItemClickListener((adapterView, view, position, l) -> {
            stateMenuAdapter.setCheckItem(position);
            binding.include.dropDownMenu.setTabText(position == 0 ? headers[0] : stateList.get(position).get("valueName").toString());
            binding.include.dropDownMenu.closeMenu();
            if (stateList.get(position).containsKey("valuel")) {
                jsonObject.put("state", stateList.get(position).get("valuel").toString());
            } else {
                jsonObject.put("state", "");
            }
            page = 1;
            getData();
        });

        mTimeView.setOnItemClickListener((adapterView, view, i, l) -> {
            timeAdapter.setCheckItem(i);
            show(time[i]);
        });

        confirm1.setOnClickListener(view -> {
            if (!TextUtils.isEmpty(causeNumber1.getText().toString())) {
                //获取输入额合同号
                house_number = causeNumber1.getText().toString();
                jsonObject.put("rscode", house_number);
                binding.include.dropDownMenu.setTabText(causeNumber1.getText().toString());
                binding.include.dropDownMenu.closeMenu();
            } else {
                binding.include.dropDownMenu.setTabText("房源编号");
                jsonObject.remove("rscode");
                binding.include.dropDownMenu.closeMenu();
            }
            getData();
            // 隐藏软键盘
            imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
        });

        confirm2.setOnClickListener(view -> {
            if (!TextUtils.isEmpty(causeNumber2.getText().toString())) {
                //获取输入小区名称
                rscode_number = causeNumber2.getText().toString();
                jsonObject.put("estate", rscode_number);
                binding.include.dropDownMenu.setTabText(causeNumber2.getText().toString());
                binding.include.dropDownMenu.closeMenu();
            } else {
                binding.include.dropDownMenu.setTabText("小区名称");
                jsonObject.remove("estate");
                binding.include.dropDownMenu.closeMenu();
            }
            getData();
            // 隐藏软键盘
            imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
        });

        adapter.setOnItemClickListener((view, o) -> {
//                System.out.println( ((Map<String,Object>)o).entrySet()  );
            Intent intent = new Intent(getActivity(), ActualDetailsActivity.class);
            intent.putExtra("applyCode", ((Map<String, Object>) o).get("applyCode").toString());
            intent.putExtra("rscode", ((Map<String, Object>) o).get("rscode").toString());
            intent.putExtra("mold", 1);
            startActivity(intent);
        });

        adapter.setOnNumberListener(rscode -> {
            Intent intent = new Intent(getActivity(), HouseDetailActivity.class);
            intent.putExtra("code", rscode);
            intent.putExtra("type", "rent");
            startActivity(intent);
        });
    }


    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (timePickerView.getTitle().equals("最早日期")) {
            startTime = DateUtil.getTimeStart(millseconds);
            timeAdapter.startTime = startTime;
        } else if (timePickerView.getTitle().equals("最晚日期")) {
            endTime = DateUtil.getTimeEnd(millseconds);
            timeAdapter.endTime = endTime;
        }
        timeAdapter.notifyDataSetChanged();
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            binding.include.dropDownMenu.setTabText(startTime + "—" + endTime);
        } else {
            binding.include.dropDownMenu.setTabText(startTime + endTime);
        }
    }

    public void show(String title) {
        TimePickerDialog timePicker = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId(title)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.yellow))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.hintColor))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.yellow))
                .setCallBack(this)
                .build();
        timePicker.show(getActivity().getSupportFragmentManager(), "year_month_day");
    }

    /**
     * 获取数据
     */
    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 10);
        jsonObject.put("pageIndex", page);
        OkHttpUtils
                .postString()
                .url(ApiConfig.ACTUAL_RENT)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //状态列表
                            stateList = JSON.parseObject(data.getJSONArray("stateList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            stateMenuAdapter.setData(stateList);
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("page").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        } else if (response.get("code").toString().equals("501")) {
                            adapter.changeMode(YfListMode.MODE_EMPTY);
                        }
                        if (binding.include.refreshLayout.isRefreshing()) {
                            binding.include.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 10 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        } else if (adapter.getData().size() > 10) {
            adapter.addFooter(R.string.is_all);
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }
}
